package com.oa.car.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.oa.car.entity.*;
import com.oa.car.mapper.CarRequireMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月7日
 */
@Service
public class CarRequireService extends BaseService<CarRequireMapper, CarRequire> {
    static Logger logger = LoggerFactory.getLogger(CarRequireService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }


    @Autowired
    CarCarDriverTplService carCarDriverTplService;

    @Autowired
    CarRequireCarDriverService carRequireCarDriverService;

    @Autowired
    CarExpenseDetailTplService carExpenseDetailTplService;

    @Autowired
    CarRequireExpenseDetailService carRequireExpenseDetailService;

    @Autowired
    CarRequireRouteService carRequireRouteService;

    @Autowired
    CarRequireRouteDetailService carRequireRouteDetailService;

    @Autowired
    CarRouteDetailTplService carRouteDetailTplService;

    @Autowired
    CarOfficeCarService carOfficeCarService;

    @Autowired
    CarDriverService carDriverService;

    @Autowired
    CarRouteTplService carRouteTplService;


    /**
     * 请在此类添加自定义函数
     */
    @Transactional
    public void save(CarRequireVo carRequireVo) {

        try {
            CarRequire carRequire = new CarRequire();
            //从vo中拷贝出来CarRequire需要的表
            BeanUtils.copyProperties(carRequireVo, carRequire);

            if (StringUtils.isEmpty(carRequire.getId())) {
                carRequire.setId(this.createKey("id"));
            } else {
                CarRequire carRequireQuery = new CarRequire(carRequire.getId());
                if (this.countByWhere(carRequireQuery) > 0) {
                    log.info("编号重复，请修改编号再提交");
                    throw new BizException("编号重复，请修改编号再提交");
                }
            }
            carRequire.setReqStatus("0");//设置请求状态为0
            carRequire.setBizFlowState("0");//审批状态为0
            //前端传过来的HasRoute = "true" | "false"
            if (carRequire.getHasRoute().equals("true")) {
                carRequire.setHasRoute("1");
            } else {
                carRequire.setHasRoute("0");
            }
            //调用方法插入
            this.insert(carRequire);
            saveOtherMessgaes(carRequireVo, carRequire);

        } catch (BizException e) {
            throw new BizException("", "");
        }

    }

    /**
     * 保存用车其他表的信息
     *
     * @param carRequireVo
     * @param carRequire
     */
    private void saveOtherMessgaes(CarRequireVo carRequireVo, CarRequire carRequire) {
        //保存车辆信息
        CarRequireCarDriver carRequireCarDriver = new CarRequireCarDriver();
        if (!StringUtils.isEmpty(carRequireVo.getCarId()) && !StringUtils.isEmpty(carRequireVo.getDriverId())) {
            carRequireCarDriver.setCarId(carRequireVo.getCarId());
            carRequireCarDriver.setDriverId(carRequireVo.getDriverId());
            carRequireCarDriver.setStartTime(carRequireVo.getReqStartTime());
            carRequireCarDriver.setEndTime(carRequireVo.getReqEndTime());
            carRequireCarDriver.setStatus("1");
            carRequireCarDriver.setCreateTime(carRequireVo.getReqTime());
            carRequireCarDriver.setRequireId(carRequire.getId());
            carRequireCarDriver.setGiveBacked("0");
        } else {
            CarCarDriverTpl carCarDriverTpl = new CarCarDriverTpl();
            carCarDriverTpl.setId(carRequireVo.getCarDriverTplId());
            CarCarDriverTpl carCarDriverTplSelect = carCarDriverTplService.selectOneObject(carCarDriverTpl);
            if (carCarDriverTplSelect == null) {
                throw new BizException("司机车辆选择出错，请重新选择");
            }
            //拷贝模板中的数据
            carRequireCarDriver.setIsTpl(carCarDriverTplSelect.getId());
            carCarDriverTplSelect.setId("");
            BeanUtils.copyProperties(carCarDriverTplSelect, carRequireCarDriver);

            carRequireCarDriver.setStartTime(carRequireVo.getReqStartTime());
            carRequireCarDriver.setEndTime(carRequireVo.getReqEndTime());
            carRequireCarDriver.setCreateTime(carRequireVo.getReqTime());
            carRequireCarDriver.setRequireId(carRequire.getId());
            carRequireCarDriver.setGiveBacked("0");
        }
        carRequireCarDriverService.insertOne(carRequireCarDriver);

        //保存费用信息
        /*//前端传来的费用模板id
        List<String> checkedExpenseDetailTpls = carRequireVo.getCheckedExpenseDetailTpls();
        if (checkedExpenseDetailTpls.size() > 0){
            checkedExpenseDetailTpls.forEach((ExpenseDetailTpl)->{
                CarRequireExpenseDetail carRequireExpenseDetail = new CarRequireExpenseDetail();

                //新建一个对象去查询CarExpenseDetailTpl的信息
                CarExpenseDetailTpl carExpenseDetailTpl = new CarExpenseDetailTpl();
                carExpenseDetailTpl.setId(ExpenseDetailTpl);
                CarExpenseDetailTpl carExpenseDetailTplSelect = carExpenseDetailTplService.selectOneObject(carExpenseDetailTpl);

                //清楚掉carExpenseDetailTplSelect的id，不然会覆盖掉前台传过来的id
                carRequireExpenseDetail.setIsTpl(ExpenseDetailTpl);
                carExpenseDetailTplSelect.setId("");

                //拷贝模板中的数据
                BeanUtils.copyProperties(carExpenseDetailTplSelect,carRequireExpenseDetail);
                carRequireExpenseDetail.setRequireId(carRequire.getId());
                //保存费用信息
                carRequireExpenseDetailService.insertOne(carRequireExpenseDetail);
            });
        }*/
        //前端传来新建的费用
        List<CarRequireExpenseDetail> carRequireExpenseDetails = carRequireVo.getCarExpenseDetailTpls();
        if (carRequireExpenseDetails.size() > 0) {
            carRequireExpenseDetails.forEach((carRequireExpenseDetail) -> {
                //保存费用信息
                carRequireExpenseDetail.setRequireId(carRequire.getId());
                carRequireExpenseDetailService.insertOne(carRequireExpenseDetail);
            });
        }

        //保存路线信息
        List<CarRequireRoute> carRequireRoutes = carRequireVo.getCarRouteTplsNew();
        if (carRequireVo.getHasRoute().equals("false")) {
            //进入这里表示规划路线，所以获取用户输入的路线信息
            if (carRequireRoutes == null || carRequireRoutes.size() <= 0) {
                throw new BizException("获取用户输入的路线信息错误！！！请重新输入");
            }
            CarRequireRoute carRequireRoute = carRequireRoutes.get(0);

            //前端传过来的HasDetail = "true" | "false"
            if (carRequireRoute.getHasDetail().equals("true")) {
                carRequireRoute.setHasDetail("1");
            } else {
                carRequireRoute.setHasDetail("0");
            }
            if (carRequireRoute.getIsSignIn().equals("true")) {
                carRequireRoute.setIsSignIn("1");
            } else {
                carRequireRoute.setIsSignIn("0");
            }
            carRequireRoute.setRequireId(carRequire.getId());
            //保存新建路线信息
            carRequireRoute = carRequireRouteService.insertOne(carRequireRoute);

            if (carRequireRoute.getHasDetail().equals("1")) {
                List<CarRequireRouteDetail> carRequireRouteDetails = carRequireVo.getCarRouteDetailTplsNew();
                if (carRequireRouteDetails != null && carRequireRouteDetails.size() > 0) {
                    CarRequireRoute finalCarRequireRoute = carRequireRoute;
                    carRequireRouteDetails.forEach((carRequireRouteDetail) -> {
                        if (carRequireRouteDetail.getIsSignIn().equals("true")) {
                            carRequireRouteDetail.setIsSignIn("1");
                        } else {
                            carRequireRouteDetail.setIsSignIn("0");
                        }
                        carRequireRouteDetail.setRouteId(finalCarRequireRoute.getId());
                        //保存子路线信息
                        carRequireRouteDetailService.insertOne(carRequireRouteDetail);
                    });
                }
            }
        } else {

            //保存模板路线信息
            CarRouteTpl carRouteTpl = carRequireVo.getCarRouteTpl();
            String carRouteTplId = carRouteTpl.getId();
            carRouteTpl.setId("");
            CarRequireRoute carRequireRoute = new CarRequireRoute();
            BeanUtils.copyProperties(carRouteTpl, carRequireRoute);

            carRequireRoute.setIsTpl(carRouteTplId);
            carRequireRoute.setDetailName(carRouteTpl.getRouteName());
            carRequireRoute.setRequireId(carRequire.getId());
            carRequireRoute = carRequireRouteService.insertOne(carRequireRoute);

            if (StringUtils.isEmpty(carRequireRoute.getHasDetail())) {
                throw new BizException("请选择路线的模板信息");
            }

            if (carRequireRoute.getHasDetail().equals("1")) {
                Map<String, Object> map = new HashMap<>();
                map.put("routeId", carRouteTplId);
//                List<CarRouteDetailTpl> carRouteDetailTpls = carRouteDetailTplService.selectListByWhereAndRouteId(map);
                List<CarRouteDetailTpl> carRouteDetailTpls = carRouteDetailTplService.selectListByWhereAndRouteId(map);

                CarRequireRoute finalCarRequireRoute = carRequireRoute;
                carRouteDetailTpls.forEach((carRouteDetailTpl) -> {
                    //将id设为空值
                    CarRequireRouteDetail carRequireRouteDetail = new CarRequireRouteDetail();
                    BeanUtils.copyProperties(carRouteDetailTpl, carRequireRouteDetail);
                    carRequireRouteDetail.setId("");
                    carRequireRouteDetail.setRouteId(finalCarRequireRoute.getId());
                    //保存信息
                    carRequireRouteDetailService.insertOne(carRequireRouteDetail);
                });
            }
        }
    }

    @Transactional
    public void deleteByPkAndInfos(CarRequire carRequire) {
        //先删除CarRequire表的数据
        int delete = this.deleteByPk(carRequire);
        //删除司机车辆的信息
        delOtherMessages(carRequire);
    }

    /**
     * 删除用车其他表的信息
     *
     * @param carRequire
     */
    private void delOtherMessages(CarRequire carRequire) {

        CarRequireCarDriver carRequireCarDriver = new CarRequireCarDriver();
        carRequireCarDriver.setRequireId(carRequire.getId());
        carRequireCarDriverService.deleteByWhere(carRequireCarDriver);

        //删除费用的信息
        CarRequireExpenseDetail carRequireExpenseDetail = new CarRequireExpenseDetail();
        carRequireExpenseDetail.setRequireId(carRequire.getId());
        carRequireExpenseDetailService.deleteByWhere(carRequireExpenseDetail);

        //删除路线的信息
        CarRequireRoute carRequireRoute = new CarRequireRoute();
        carRequireRoute.setRequireId(carRequire.getId());

        //获取路线的信息
//        CarRequireRoute selectOneObject = carRequireRouteService.selectOne("selectOneObjectByWhere", carRequireRoute);
        CarRequireRoute selectOneObject = (CarRequireRoute) carRequireRouteService.selectOneById(carRequireRoute);
        carRequireRouteService.deleteByWhere(carRequireRoute);

        if (selectOneObject != null && selectOneObject.getHasDetail().equals("1")) {
            //删除子路线的信息
            CarRequireRouteDetail carRequireRouteDetail = new CarRequireRouteDetail();
            carRequireRouteDetail.setRouteId(selectOneObject.getId());
            carRequireRouteDetailService.deleteByWhere(carRequireRouteDetail);
        }
    }

    /**
     * 获取申请用车的信息
     *
     * @param carRequire
     * @return
     */
    public Map<String, Object> getMessageById(Map<String, Object> carRequire) {

        String id = carRequire.get("id").toString();
        Map<String, Object> m = new HashMap<>();
        Tips tips = new Tips("查询成功");
        CarRequireVo carRequireVo = new CarRequireVo();

        CarRequire carRequireObj = new CarRequire();
        carRequireObj.setId(id);
        carRequireObj = this.selectOneObject(carRequireObj);
        BeanUtils.copyProperties(carRequireObj, carRequireVo);

        CarRequireCarDriver carRequireCarDriver = new CarRequireCarDriver();
        carRequireCarDriver.setRequireId(id);
        List<CarRequireCarDriver> carRequireCarDrivers = carRequireCarDriverService.selectListByWhere(carRequireCarDriver);
        if (carRequireCarDrivers == null || carRequireCarDrivers.size() <= 0) {
            throw new BizException("获取车辆司机信息错误！！");
        }
        carRequireCarDriver = carRequireCarDrivers.get(0);

        //判断是否使用模板
        if (!StringUtils.isEmpty(carRequireCarDriver.getIsTpl())) {

            Map<String, Object> selectMap = new HashMap<>();
            selectMap.put("id", carRequireCarDriver.getIsTpl());
            List<Map<String, Object>> resultMaps = carCarDriverTplService.selectListMapByWhereAndCarDriver(selectMap);
            if (resultMaps != null && resultMaps.size() > 0) {
                Map<String, Object> map = resultMaps.get(0);
                String carName = (String) map.get("carName");
                String driverUsername = (String) map.get("driverUsername");
                //汽车名：宝马5系-----司机名：胡钛河
                carRequireVo.setCarDriverTplName(carName + "-----" + driverUsername);
            }
            carRequireVo.setCarDriverTplId(carRequireCarDriver.getIsTpl());

        } else {
            CarDriver carDriver = new CarDriver();
            carDriver.setDriverId(carRequireCarDriver.getDriverId());
            carDriver = carDriverService.selectOneObject(carDriver);

            CarOfficeCar carOfficeCar = new CarOfficeCar();
            carOfficeCar.setId(carRequireCarDriver.getCarId());
            carOfficeCar = carOfficeCarService.selectOneObject(carOfficeCar);

            carRequireVo.setCarId(carOfficeCar.getId());
            carRequireVo.setCarName(carOfficeCar.getCarName());
            carRequireVo.setDriverId(carDriver.getDriverId());
            carRequireVo.setDriverName(carDriver.getDriverUsername());
        }

        //获取用车的费用信息
        CarRequireExpenseDetail carRequireExpenseDetail = new CarRequireExpenseDetail();
        carRequireExpenseDetail.setRequireId(id);
        List<CarRequireExpenseDetail> carRequireExpenseDetails = carRequireExpenseDetailService.selectListByWhere(carRequireExpenseDetail);
        carRequireVo.setCarExpenseDetailTpls(carRequireExpenseDetails);

        //获取路线信息
        CarRequireRoute carRequireRoute = new CarRequireRoute();
        carRequireRoute.setRequireId(id);
        List<CarRequireRoute> carRequireRoutes = carRequireRouteService.selectListByWhere(carRequireRoute);
        if (carRequireRoutes == null || carRequireRoutes.size() <= 0) {
            throw new BizException("获取路线信息错误！！");
        }
        carRequireRoute = carRequireRoutes.get(0);

        if (!StringUtils.isEmpty(carRequireRoute.getIsTpl())) {
            CarRouteTpl carRouteTpl = new CarRouteTpl();
            //carRouteTpl = carRouteTplService.selectOneObject(carRouteTpl);
            BeanUtils.copyProperties(carRequireRoute, carRouteTpl);
            carRouteTpl.setId(carRequireRoute.getIsTpl());
            carRouteTpl.setRouteName(carRequireRoute.getDetailName());
            carRequireVo.setCarRouteTpl(carRouteTpl);
        } else {
            List<CarRequireRoute> carRouteTplsNew = new ArrayList<>();
            carRouteTplsNew.add(carRequireRoute);

            carRequireVo.setCarRouteTplsNew(carRouteTplsNew);
            if (carRequireRoute.getHasDetail().equals("1")) {
                List<CarRequireRouteDetail> carRouteDetailTplsNew = new ArrayList<>();
                CarRequireRouteDetail carRequireRouteDetail = new CarRequireRouteDetail();
                carRequireRouteDetail.setRouteId(carRequireRoute.getId());
                carRouteDetailTplsNew = carRequireRouteDetailService.selectListByWhere(carRequireRouteDetail);
                carRequireVo.setCarRouteDetailTplsNew(carRouteDetailTplsNew);
            }
        }
        m.put("data", carRequireVo);
        m.put("tips", tips);
        return m;
    }


    /**
     * 修改用车申请的信息
     *
     * @param carRequireVo
     * @return
     */
    @Transactional
    public void editCarRequireMessage(CarRequireVo carRequireVo) {

        Tips tips = new Tips("成功更新一条数据");
        try {
            CarRequire carRequire = new CarRequire();
            //从vo中拷贝出来CarRequire需要的表
            BeanUtils.copyProperties(carRequireVo, carRequire);
            //前端传过来的HasRoute = "true" | "false"
            if (carRequire.getHasRoute().equals("true")) {
                carRequire.setHasRoute("1");
            } else {
                carRequire.setHasRoute("0");
            }
            //更新申请表的记录
            this.updateByPk(carRequire);
            //删除其他表的信息
            delOtherMessages(carRequire);
            //保存其他表的信息
            saveOtherMessgaes(carRequireVo,carRequire);

        } catch (BizException e) {
            tips = e.getTips();
            logger.error("", e);
            throw new BizException(tips);
        }
    }
}
